from django.urls import resolve
from rest_framework.response import Response


def get_policy_attribute_class(request, config):
    """
    将请求与配置数据进行匹配，返回响应的策略属性类
    config: 为字典类型，key: url的name属性值，value: 用于返回的属性值
    配置示例如下：
    serializer_dict = {
        'user-name-check': UsernameSerializer,
        'user-email-check': EmailSerializer,
        'user-password-check': PasswordSerializer,
        'user-set-password': SetPasswordSerializer,
        'user-list': {
            'POST': CreateUserSerializer,
            'default': UserSerializer
        },
        'user-detail': {
            'default': UserSerializer
        },
        'user-register-captcha': {
            'default': NoneSerializer
        },
        'default': UserSerializer
    }
    """
    url_name = resolve(request.path).url_name
    # print(url_name)
    attribute_class = config.get(url_name, config['default'])
    if isinstance(attribute_class, (dict,)):
        return attribute_class.get(request.method, attribute_class['default'])
    else:
        return attribute_class


class GetSerializerClassMixin:
    def get_serializer_class(self):
        serializer_dict = getattr(self, 'serializer_dict', None)
        if not serializer_dict:
            return super().get_serializer_class()
        return get_policy_attribute_class(self.request, serializer_dict)


class GetPermissionsMixin:
    def get_permissions(self):
        permissions_dict = getattr(self, 'permissions_dict', None)
        if not permissions_dict:
            return super().get_permissions()
        permission_classes = get_policy_attribute_class(self.request, permissions_dict)
        return [permission() for permission in permission_classes]


class DestroyModelMixin:
    """
    在RESTframework原生DestroyModelMixin上修改返回状态码
    """
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response('删除成功')

    def perform_destroy(self, instance):
        instance.delete()
